/**
 * ContextLoader.java
 *
 * Copyright 2008 easou, Inc. All Rights Reserved.
 */
package me.xxy.mq.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ContextLoader {
	
	private static final Logger LOG = LoggerFactory.getLogger(ContextLoader.class);

	private static ClassPathXmlApplicationContext context;

	public synchronized static ClassPathXmlApplicationContext getContext() {
		if (context == null) {
			LOG.info("-[初始化应用程序上下文]-");
			context = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
			LOG.info("-[初始化应用程序上下文完毕]-");
		}
		return context;
	}

	public synchronized static ClassPathXmlApplicationContext getContext(String... configLocations) {
		if (context == null) {
			LOG.info("-[初始化应用程序上下文]-");
			context = new ClassPathXmlApplicationContext(configLocations);
			LOG.info("-[初始化应用程序上下文完毕]-");
		}
		return context;
	}

	public synchronized static void closeContext() {
		if (context != null) {
			LOG.info("-[关闭应用程序上下文]-");
			// 关闭上下文,如果其中有定时任务，则其中的定时任务调度线程会正常停止，并且它还会等正在运行的定时任务运行完毕，然后才退出
			context.close();
			context = null;
			LOG.info("-[应用程序上下文关闭完成]-");
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		if (name == null) {
			return null;
		}
		return (T) (ContextLoader.getContext().getBean(name));
	}
}
